package org.example.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.CurrentHolder;
import org.example.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
/**
 * 令牌拦截器
 */
@SuppressWarnings("all")
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("token");
        //判断token是否存在，如果不存在，则返回错误结果（401信息）
        if(token==null||token.isEmpty()){
            log.info("token不存在，返回错误结果");
            response.setStatus(401);
            return false;
        }
        //如果存在，则解析token，如果解析失败，则返回错误结果（401信息）
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前员工登录ID为：{},存入ThreadLocal中",empId);
        } catch (Exception e) {
            log.info("令牌不合法，返回错误结果");
            response.setStatus(401);
            return false;
        }
        //如果解析成功，则放行
        log.info("令牌合法，放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        CurrentHolder.remove();
    }
}
